package com.linh.web.spring;

import java.io.IOException;

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.ResourcePropertySource;

/**
 * 
 * @author Linh Initialise spring Environment properties and set active profile
 */
@Configuration
public class EnvironmentInitialiser implements
		ApplicationContextInitializer<ConfigurableApplicationContext> {

	public void initialize(ConfigurableApplicationContext applicationContext) {
		String propertyPath = "";
		String activeProfile = System.getProperty("spring.active.profile");
		ConfigurableEnvironment env = applicationContext.getEnvironment();
		MutablePropertySources mutablePropertySources = env
				.getPropertySources();
		ClassPathResource appClassPathResource = new ClassPathResource(
				propertyPath);
		ResourcePropertySource resourcePropertySource;
		try {
			resourcePropertySource = new ResourcePropertySource(
					appClassPathResource);
			mutablePropertySources.addFirst(resourcePropertySource);
			env.setActiveProfiles(activeProfile);
		} catch (IOException e) {
			throw new RuntimeException("Failed to initialise application", e);
		}

	}

}
